﻿using Furion.DatabaseAccessor;
using Furion.DatabaseAccessor.Extensions;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using Admin.NET.Core;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;
using Microsoft.AspNetCore.Http;
using System.Text;
using System.Web;

namespace Admin.NET.Application
{
    /// <summary>
    /// 托盘信息服务
    /// </summary>
    [ApiDescriptionSettings("自己的业务", Name = "WmsContainer", Order = 100)]
    [Route("api/[Controller]")]
    public class WmsContainerService : IWmsContainerService, IDynamicApiController, ITransient
    {
        private readonly IRepository<WmsContainer,MasterDbContextLocator> _wmsContainerRep;
        private readonly IRepository<SysDictType, MasterDbContextLocator> _sysDictTypeRep;
        private readonly IRepository<SysDictData, MasterDbContextLocator> _sysDictDataRep;
        private readonly ISysExcelTemplateService _sysExcelTemplateService;
        private readonly static object _lock = new();

        /// <summary>
        /// 构造函数
        /// </summary>
        public WmsContainerService(
             IRepository<WmsContainer,MasterDbContextLocator> wmsContainerRep
            ,IRepository<SysDictType, MasterDbContextLocator> sysDictTypeRep
            ,IRepository<SysDictData, MasterDbContextLocator> sysDictDataRep
            ,ISysExcelTemplateService sysExcelTemplateService
        )
        {
             _wmsContainerRep = wmsContainerRep;
             _sysDictTypeRep = sysDictTypeRep;
             _sysDictDataRep = sysDictDataRep;
             _sysExcelTemplateService = sysExcelTemplateService;
        }

        /// <summary>
        /// 分页查询托盘信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("page")]
        public async Task<PageResult<WmsContainerOutput>> Page([FromQuery] WmsContainerSearch input)
        {
            var wmsContainers = await _wmsContainerRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(input.ContainerCode), u => EF.Functions.Like(u.ContainerCode, $"%{input.ContainerCode.Trim()}%"))
                .Where(input.ContainerType != null, u => u.ContainerType == input.ContainerType)
                .Where(input.ContainerStatus != null, u => u.ContainerStatus == input.ContainerStatus)
                .Where(input.SpecLength != null, u => u.SpecLength == input.SpecLength)
                .Where(input.SpecWidth != null, u => u.SpecWidth == input.SpecWidth)
                .Where(input.ContainerCategory != null, u => u.ContainerCategory == input.ContainerCategory)
                .Where(input.WorkShopType != null, u => u.WorkShopType == input.WorkShopType)
                .OrderBy(PageInputOrder.OrderBuilder<WmsContainerSearch>(input))
                .ProjectToType<WmsContainerOutput>()
                .ToADPagedListAsync(input.PageNo, input.PageSize);
            return wmsContainers;
        }

        /// <summary>
        /// 不分页查询托盘信息列表
        /// </summary>
        /// <param name="input">托盘信息查询参数</param>
        /// <returns>(托盘信息)实例列表</returns>
        [HttpGet("listNonPage")]
        public async Task<List<WmsContainerOutput>> ListNonPageAsync([FromQuery] WmsContainerSearchNonPage input)
        {
            var pContainerCode = input.ContainerCode?.Trim() ?? "";
            var pContainerType = input.ContainerType;
            var pContainerStatus = input.ContainerStatus;
            var pSpecLength = input.SpecLength;
            var pSpecWidth = input.SpecWidth;
            var pContainerCategory = input.ContainerCategory;
            var pWorkShopType = input.WorkShopType;
            var wmsContainers = await _wmsContainerRep.DetachedEntities
                .Where(!string.IsNullOrEmpty(pContainerCode), u => EF.Functions.Like(u.ContainerCode, $"%{pContainerCode}%")) 
                .Where(pContainerType != null, u => u.ContainerType == pContainerType)
                .Where(pContainerStatus != null, u => u.ContainerStatus == pContainerStatus)
                .Where(pSpecLength != null, u => u.SpecLength == pSpecLength)
                .Where(pSpecWidth != null, u => u.SpecWidth == pSpecWidth)
                .Where(pContainerCategory != null, u => u.ContainerCategory == pContainerCategory)
                .Where(pWorkShopType != null, u => u.WorkShopType == pWorkShopType)
            .OrderBy(PageInputOrder.OrderNonPageBuilder(input))
            .ProjectToType<WmsContainerOutput>()
            .ToListAsync();
            return wmsContainers;
        }


        /// <summary>
        /// 增加托盘信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task Add(AddWmsContainerInput input)
        {
            var isExist = await _wmsContainerRep.AnyAsync(u => u.ContainerCode == input.ContainerCode, false);
            if (isExist) throw Oops.Oh($"当前托盘已存在，新增失败！");

            var ContainerInfo = input.Adapt<WmsContainer>();
            ContainerInfo.ContainerStatus = ContainerStatus.KOUXIAN;
            ContainerInfo.AssetNo = "N/A";
            ContainerInfo.ContainerCategory = ContainerCategory.GZP;
            ContainerInfo.ErpNo = "N/A"; 
            ContainerInfo.IsVirtually = YesOrNot.N;
            ContainerInfo.WorkShopType = LesWorkShopType.FAPAOCHEJIAN;
            await _wmsContainerRep.InsertAsync(ContainerInfo);
            //string ContainerCode = "ZHONGTONG";
            //if (input.SpecLength == 1250)
            //{
            //    ContainerCode = "YKA";
            //}
            //else if (input.SpecLength == 1050)
            //{
            //    ContainerCode = "YKB";
            //}
            //else if (input.SpecLength == 800)
            //{
            //    ContainerCode = "YKC";
            //}
            //var wmsContainerModal = await _wmsContainerRep.DetachedEntities.Where(u => u.ContainerCode.Contains(input.ContainerCode))
            //    .ProjectToType<WmsContainerOutput>()
            //    .OrderByDescending(u => u.ContainerCode)
            //    .FirstOrDefaultAsync();
            //int a = 0;
            //if (wmsContainerModal != null)
            //{
            //    a = Convert.ToInt32(wmsContainerModal.ContainerCode.Substring(wmsContainerModal.ContainerCode.Length - 5));
            //}
            //for (int i = a + 1; i <= a + input.Quantity; i++)
            //{
            //    var wmsContainer = input.Adapt<WmsContainer>();
            //    wmsContainer.AssetNo = "N/A";
            //    wmsContainer.ErpNo = "N/A";
            //    wmsContainer.IsVirtually = YesOrNot.N;
            //    wmsContainer.IsDeleted = false;;
            //    wmsContainer.ContainerCode = ContainerCode + i.ToString("00000");
            //    await _wmsContainerRep.InsertAsync(wmsContainer);
            //}
        }

        /// <summary>
        /// 删除托盘信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task Delete(DeleteWmsContainerInput input)
        {
            var wmsContainer = await _wmsContainerRep.FirstOrDefaultAsync(u => u.Id == input.Id);
            await _wmsContainerRep.DeleteAsync(wmsContainer);
        }

        /// <summary>
        /// 更新托盘信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("edit")]
        public async Task Update(UpdateWmsContainerInput input)
        {
            var isExist = await _wmsContainerRep.AnyAsync(u => u.Id == input.Id, false);
            if (!isExist) throw Oops.Oh(ErrorCode.D3000);

            var wmsContainer = input.Adapt<WmsContainer>();
            await _wmsContainerRep.UpdateAsync(wmsContainer,ignoreNullValues:true);
        }

        /// <summary>
        /// 获取托盘信息
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("detail")]
        public async Task<WmsContainerOutput> Get([FromQuery] QueryeWmsContainerInput input)
        {
            return (await _wmsContainerRep.DetachedEntities.FirstOrDefaultAsync(u => u.Id == input.Id)).Adapt<WmsContainerOutput>();
        }

        /// <summary>
        /// 获取托盘信息列表
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet("list")]
        public async Task<List<WmsContainerOutput>> List([FromQuery] WmsContainerInput input)
        {
            return await _wmsContainerRep.DetachedEntities.ProjectToType<WmsContainerOutput>().ToListAsync();
        }    
         /// <summary>
        /// Excel模板导入托盘信息功能
        /// </summary>
        /// <param name="file">Excel模板文件</param>
        /// <param name="importExcelType">Excel导入方式</param>
        /// <returns>导入的记录数</returns>
        [HttpPost("fromExcel")]
        public async Task<int> FromExcelAsync(IFormFile file, [FromQuery] ImportExcelType importExcelType)
        {
            int size = 200;
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsContainer", "v2");
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var keys = excelTemplate.UnionUniqueFields.Split(",") ?? Array.Empty<string>();
            for (var i = 0; i < keys.Length; i++) 
            {
                keys[i] = keys[i]?.Trim() ?? string.Empty;
            }
            ExcelUtil.FromExcel(file, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, out List<string> headers, out List<List<object>> data, out string sheetName);
            List<WmsContainerOutput> wmsContainerList = DataConvertUtil.ToObjectList(headers, data, sheetName, keys, excelTemplate?.DataStartLine ?? 2, out Dictionary<string, WmsContainerOutput> dict);
            List<Dictionary<string, object>> uniqueKeyValueDictList = wmsContainerList.ParseUniqueKeyValueDictList(keys.ToList(), excelTemplate?.DataStartLine ?? 2, sheetName);
            var filters = DataConvertUtil.GetExpressionListByUniqueDict<WmsContainer>(keys.ToList(), uniqueKeyValueDictList, size);
            var selectKeys = keys.ToList();
            if(!selectKeys.Contains("Id")) selectKeys.Add("Id");
            var selector = DataConvertUtil.GetSelectExpressionListByUniqueDict<WmsContainer, WmsContainerOutput>(selectKeys);
            List<WmsContainer> updates = new();
            List<WmsContainer> adds = new();

            lock (_lock)
            {
                foreach (var filter in filters)
                {
                    var wmsContainerExistSubList = _wmsContainerRep.Where(filter).Select(selector).ToList();
                    wmsContainerExistSubList.ForEach(x => 
                    {
                        var k = DataConvertUtil.GetKey(x, keys);
                        if (dict.ContainsKey(k)) dict[k].Id = x.Id;
                    });
                }
                foreach (var wmsContainer in wmsContainerList) 
                {
                    if (wmsContainer.Id > 0)
                    {
                        if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.Add(wmsContainer.Adapt<WmsContainer>());
                    }
                    else 
                    {
                        adds.Add(wmsContainer.Adapt<WmsContainer>());
                    }
                }

                if (importExcelType == ImportExcelType.ADD_AND_UPDATE) updates.ForEach(x => _wmsContainerRep.Update(x));
                

                var maxId = _wmsContainerRep.DetachedEntities.OrderByDescending(x => x.Id).Select(x => x.Id).FirstOrDefault();
                adds.ForEach(x => x.Id = ++maxId);    
                Db.GetDbContext().Set<WmsContainer>().AddRange(adds);  
                Db.GetDbContext().SaveChanges();
               
            }
            await Task.CompletedTask;
            return adds.Count;
        }

        /// <summary>
        /// 根据版本下载托盘信息的Excel导入模板
        /// </summary>
        /// <param name="version">模板版本</param>
        /// <returns>下载的模板文件</returns>
        [HttpGet("downloadExcelTemplate")]
        public async Task<IActionResult> DownloadExcelTemplate([FromQuery] string version)
        {
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsContainer", version);
            if (excelTemplate == null) throw Oops.Oh(ErrorCode.Excel002);
            var path = Path.Combine(@"\", excelTemplate.TemplateFileName);
            Stream ms = FileUtil.Download(path, excelTemplate.TemplateFileName);
            var fileName = HttpUtility.UrlEncode($"{excelTemplate.Name}导入模板.xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
        /// <summary>
        /// 根据托盘信息查询参数导出Excel
        /// </summary>
        /// <param name="input">托盘信息查询参数</param>
        /// <returns>导出的Excel文件</returns>
        [HttpGet("toExcel")]
        public async Task<IActionResult> ToExcelAsync([FromQuery] WmsContainerSearchNonPage input)
        {
            var wmsContainerList = await ListNonPageAsync(input);
            MemoryStream ms = new();
            DataConvertUtil.ToExcelData(wmsContainerList, _sysDictTypeRep, _sysDictDataRep, out List<string> headers, 
                out List<List<object>> data, out string sheetName);
            var excelTemplate = await _sysExcelTemplateService.GetByAppNameAndClassNameAndVersionAsync("WmsContainer", "v1");
            if (excelTemplate != null)
            {
                ExcelUtil.ToExcel(excelTemplate.TemplateFileName, headers, data, sheetName, excelTemplate.HeadStartLine, excelTemplate.DataStartLine, ms);
            }
            else 
            {
                ExcelUtil.ToExcel(headers, data, sheetName, ms);
            }
            ms.Position = 0;
            var fileName = HttpUtility.UrlEncode($"{sheetName}[{DateTimeOffset.Now:yyyy-MM-dd}].xlsx", Encoding.GetEncoding("UTF-8"));
            return new FileStreamResult(ms, "application/octet-stream") { FileDownloadName = fileName };
        }
    }
}
